package com.zjw.study.thread04_sharedata;

/**
 * 多个线程数据共享，且线程同步，保证数据执行顺序
 * 
 * </p>
 * 习题和下面一样
 * {@link MoreShare}
 * @author Administrator
 *
 */
public class MoreShareSynchronized {
	public static void main(String[] args) {
		MoreShareSynchronized mss = new MoreShareSynchronized();
		mss.share01();
	}
	
	/**
	 * 答案
	 */
	void share01() {
		MoreShareData sd = new MoreShareData();
		for (int i = 0; i < 2; i++) {
			new ThreadIncrement(sd);
			new ThreadDecrement(sd);
		}
	}

}

/**
 * 数据共享操作
 * @author Administrator
 *
 */
class MoreShareData {
	/**
	 * 共享的变量
	 */
	int j = 0;
	
	/**
	 * 数据+
	 */
	void increment() {
		j++;
		System.out.println(Thread.currentThread().getName() + " -- increment , j=" + j);
	}
	/**
	 * 数据-
	 */
	void decrement() {
		j--;
		System.out.println(Thread.currentThread().getName() + " -- decrement , j=" + j);
	}
}

/**
 * 加的线程类
 * @author Administrator
 *
 */
class ThreadIncrement extends Thread {
	private MoreShareData sd;
	
	public ThreadIncrement(MoreShareData sd) {
		this.sd = sd;
		this.start();
	}
	
	@Override
	public void run() {
		sd.increment();
	}
}

/**
 * 减的线程类
 * @author Administrator
 *
 */
class ThreadDecrement extends Thread {
	private MoreShareData sd;
	
	public ThreadDecrement(MoreShareData sd) {
		this.sd = sd;
		this.start();
	}
	
	@Override
	public void run() {
		sd.decrement();
	}
}